﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace IRCClient
{
    class Program
    {
        static byte[] data = new byte[1024];

        static void Main(string[] args)
        {
            Console.WriteLine("Starting the IRC Client...");

            string IP = "127.0.0.1";
            int portNumber = 9000;

            if (args.Count() > 0)
                IP = args[0];

            if (args.Count() > 1)
                portNumber = int.Parse(args[1]);

            Socket newsock = new Socket(AddressFamily.InterNetwork,
              SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint iep = new IPEndPoint(IPAddress.Parse(IP), portNumber);

            Console.WriteLine("Connecting to IRC Server (irc://{0}:{1})", IP, portNumber);
            newsock.Connect(iep);

            Console.WriteLine("Connected");

            newsock.BeginReceive(data, 0, data.Length, SocketFlags.None, new AsyncCallback(HandleReceive), newsock);

            while (true)
            {
                Console.Write(">");
                string message = Console.ReadLine();
                byte[] messageData = System.Text.Encoding.ASCII.GetBytes(message);
                newsock.BeginSend(messageData, 0, messageData.Length, SocketFlags.None, new AsyncCallback(FinalizeSend), newsock);
                System.Threading.Thread.Sleep(1000);
            }
        }

        static void HandleReceive(IAsyncResult result)
        {
            Socket socket = (Socket)result.AsyncState;
            int bytesReceived = 0;
            try
            {
                bytesReceived = socket.EndReceive(result);
            }
            catch
            {
            }

            if (bytesReceived == 0)
            {
                Console.WriteLine("Server Terminated the connection");
                System.Environment.Exit(0);
            }

            string message = System.Text.Encoding.ASCII.GetString(data, 0, bytesReceived);
            Console.WriteLine(message);

            socket.BeginReceive(data, 0, data.Length, SocketFlags.None, new AsyncCallback(HandleReceive), socket);
        }

        static void FinalizeSend(IAsyncResult result)
        {
            Socket socket = (Socket)result.AsyncState;
            socket.EndSend(result);
        }
    }
}
